package com.sci99.study01.security;

import com.sci99.study01.entity.SysRole;
import com.sci99.study01.entity.SysUser;
import com.sci99.study01.entity.SysUserRole;
import com.sci99.study01.service.SysRoleService;
import com.sci99.study01.service.SysUserRoleService;
import com.sci99.study01.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/*******************************************************
 * 作    者：lichao  =^_^=
 * 创建日期：2021/1/4 13:54
 * 电子邮箱：lichao@sci99.com
 * 版 本 号：V1.0.0
 * 版权所有：2004-2021 山东卓创资讯股份有限公司，并保留所有权利。
 * 网    址：http://www.sci99.com/
 ******************************************************/
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities=new ArrayList<>();

        SysUser user=userService.selectByName(username);

        if(user==null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        List<SysUserRole> userRoles=userRoleService.listByUserId(user.getId());
        for (SysUserRole userRole:userRoles){
            SysRole role=roleService.selectById(userRole.getRoleId());
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        return  new User(user.getName(),user.getPassword(),authorities);
    }
}
